﻿using System;
using System.IO;

namespace Lucene.Net.Store.S3 {

	public class IndexOutput : Lucene.Net.Store.IndexOutput {
		private readonly Directory s3Directory;
		private Lucene.Net.Store.Directory cacheDirectory;
		private Lucene.Net.Store.IndexOutput indexOutput;
		private readonly String name;

		public IndexOutput(Directory s3Directory, String name) {
			this.s3Directory = s3Directory;
			this.indexOutput = this.s3Directory.CacheDirectory.CreateOutput(name);
			this.cacheDirectory = this.s3Directory.CacheDirectory;
			this.name = name;
		}

		public override void Close() {
			this.indexOutput.Flush();
			//Int64 originalLength = this.indexOutput.Length();
			this.indexOutput.Close();

			StreamInput stream = new StreamInput(this.cacheDirectory.OpenInput(name));
			this.s3Directory.WriteFile(name, stream);
			stream.Dispose();
			this.indexOutput = null;
		}

		public override void Flush() {
			this.indexOutput.Flush();
		}

		public override Int64 GetFilePointer() {
			return this.indexOutput.GetFilePointer();
		}

		public override Int64 Length() {
			return this.indexOutput.Length();
		}

		public override void Seek(Int64 pos) {
			this.indexOutput.Seek(pos);
		}

		public override void WriteByte(Byte b) {
			this.indexOutput.WriteByte(b);
		}

		public override void WriteBytes(Byte[] b, Int32 offset, Int32 length) {
			this.indexOutput.WriteBytes(b, offset, length);
		}
	}
}